package com.dingjiaxiong.xiongbi_backend.api;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.dingjiaxiong.xiongbi_backend.common.ErrorCode;
import com.dingjiaxiong.xiongbi_backend.exception.BusinessException;
import com.google.gson.Gson;
import com.google.gson.JsonObject;

public class OpenAIChatClient {
    private static final String API_URL = "https://api.qyfxw.cn/v1/chat/completions";
    private final String apiKey;

    public OpenAIChatClient(String apiKey) {
        this.apiKey = apiKey;
    }

    public String chat(String message) throws Exception {
        JSONObject requestBody = new JSONObject();
        requestBody.set("model","gpt-3.5-turbo" );
        JSONArray messages = new JSONArray();
        String systemPrompt = "\"你是一个数据分析师和前端开发专家，接下来我会按照以下固定格式给你提供内容：\\n\" +\n" +
                "                \"分析需求：\\n\" +\n" +
                "                \"{数据分析的需求或者目标}\\n\" +\n" +
                "                \"原始数据：\\n\" +\n" +
                "                \"{csv格式的原始数据，用,作为分隔符}\\n\" +\n" +
                "                \"请根据这两部分内容，按照以下指定格式生成内容（此外不要输出任何多余的开头、结尾、注释）\\n\" +\n" +
                "                \"【【【【【\\n\" +\n" +
                "                \"{前端 Echarts V5 的 option 配置对象的json代码，合理地将数据进行可视化，不要生成任何多余的内容，比如注释}\\n\" +\n" +
                "                \"【【【【【\\n\" +\n" +
                "                \"{明确的数据分析结论、越详细越好，不要生成多余的注释}\"";
        messages.add(new JSONObject().set("role", "system").set("content", systemPrompt));
        messages.add(new JSONObject().set("role", "user").set("content", message));
        requestBody.set("messages",messages);
        HttpResponse response = HttpRequest.post(API_URL)
                .header("Authorization", "Bearer " + apiKey)
                .header("Content-Type", "application/json")
                .body(requestBody.toString())
                .execute();
        if (response.getStatus() != 200){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, response.getStatus()+ " AI 响应错误,"+response.body());
        }
        JSONObject responseJson = JSONUtil.parseObj(response.body());
        JSONArray choices = responseJson.getJSONArray("choices");
        if (choices.isEmpty()) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"API返回结果为空");
        }
        // 提取生成的文本
        return choices.getJSONObject(0)
                .getJSONObject("message")
                .getStr("content");
    }




//
//        URL url = new URL(API_URL);
//        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//        connection.setRequestMethod("POST");
//        connection.setRequestProperty("Content-Type", "application/json");
//        connection.setRequestProperty("Authorization", "Bearer " + apiKey);
//        connection.setDoOutput(true);
//
//        Gson gson = new Gson();
//        JsonObject requestBody = new JsonObject();
//        requestBody.addProperty("model", "gpt-3.5-turbo");
//        JsonObject messageObj = new JsonObject();
//        messageObj.addProperty("role", "user");
//        String systemPrompt = "\"你是一个数据分析师和前端开发专家，接下来我会按照以下固定格式给你提供内容：\\n\" +\n" +
//                "                \"分析需求：\\n\" +\n" +
//                "                \"{数据分析的需求或者目标}\\n\" +\n" +
//                "                \"原始数据：\\n\" +\n" +
//                "                \"{csv格式的原始数据，用,作为分隔符}\\n\" +\n" +
//                "                \"请根据这两部分内容，按照以下指定格式生成内容（此外不要输出任何多余的开头、结尾、注释）\\n\" +\n" +
//                "                \"【【【【【\\n\" +\n" +
//                "                \"{前端 Echarts V5 的 option 配置对象的json代码，合理地将数据进行可视化，不要生成任何多余的内容，比如注释}\\n\" +\n" +
//                "                \"【【【【【\\n\" +\n" +
//                "                \"{明确的数据分析结论、越详细越好，不要生成多余的注释}\"";
//
//        messageObj.addProperty("content", systemPrompt);
//        messageObj.addProperty("content",message);
//        requestBody.add("messages", gson.toJsonTree(new JsonObject[]{messageObj}));
//
//        byte[] input = requestBody.toString().getBytes(StandardCharsets.UTF_8);
//        try (DataOutputStream dos = new DataOutputStream(connection.getOutputStream())) {
//            dos.write(input, 0, input.length);
//        }
//
//        int responseCode = connection.getResponseCode();
//        StringBuilder response = new StringBuilder();
//        try (BufferedReader br = new BufferedReader(
//                new InputStreamReader(responseCode == 200 ? connection.getInputStream() : connection.getErrorStream(), StandardCharsets.UTF_8))) {
//            String responseLine;
//            while ((responseLine = br.readLine()) != null) {
//                response.append(responseLine.trim());
//            }
//        }
//
//        if (responseCode != 200) {
//            throw new Exception("HTTP request failed with code: " + responseCode + ", response: " + response.toString());
//        }
//
//        JsonObject responseJson = gson.fromJson(response.toString(), JsonObject.class);
//        return responseJson.getAsJsonArray("choices").get(0).getAsJsonObject().getAsJsonObject("message").get("content").getAsString();
//    }
}